package com.nowcoder.community.actuator;/**
 * @description:
 * @Author HP
 * @create 2022/1/6 13:12
 */

import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author HP
 * @create 2022-01-06 13:12
 * @desc
 **/
@Component
@Endpoint(id="database")
public class DatabaseEndpoint {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);

    //可通过连接池或连接参数（manager）获取连接，这里用连接池

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @ReadOperation //表示是用get请求来访问
    public String checkConnection(){
        try (
                Connection conn = dataSource.getConnection();
        ){
            return CommunityUtil.getJSONString(0,"获取连接成功！");
        } catch (SQLException e) {
            logger.error("获取连接失败："+e.getMessage());
            return CommunityUtil.getJSONString(1,"获取连接失败！");
        }
    }
}
